package org.piaohao.util.database;

import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.List;

/**
 * 此工具类，可以根据数据库表自动生成实体类，生成的实体类包含静态dao引用，以及各列字段， 生成的列字段对应了java的数据类型 Created on :
 * 2013-5-6, 21:58:11
 *
 * @author piaohao
 */
public class AutoCreateEntity {

    private static final String url = "jdbc:mysql://localhost/transport_safe";
    private static final String name = "root";
    private static final String password = "root";

    /*注册jfinal数据库插件*/
    static {
        C3p0Plugin cp = new C3p0Plugin(url, name, password);
        cp.start();//启动插件
        DbKit.setDataSource(cp.getDataSource());
    }

    /**
     * 根据数据库表，自动生成实体文件
     *
     * @param path 文件存放路径
     * @param packageName 包名
     * @param withField 是否生成属性字段
     */
    public static void process(String path, String packageName, boolean withField) {
        try {
            List<Object> objs = Db.query("select table_name from information_schema.tables where table_schema=?",
                    "transport_safe");//查询所有表名
            for (int i = 0; i < objs.size(); i++) {
                String tableName = (String) objs.get(i);
                String className = StringKit.firstCharToUpperCase(tableName);
                String result = "package " + packageName + ";\n\n";
                result += "import com.jfinal.plugin.activerecord.Model; \n\n";
                result += "public class " + className + " extends Model<" + className + ">{\n\n";
                result += "    public static final " + className + " dao = new " + className + "();\n\n";
                if (withField) {
                    result += "    /**表名**/ \n";
                    result += "    public static String TABLE = \"" + tableName + "\";\n";
                    List<Object> records = Db.query("select * from information_schema.columns where table_schema=? and table_name=?",
                            "transport_safe", tableName);//查询表中所有列名
                    for (int j = 0; j < records.size(); j++) {
                        String fieldName = (String) ((Object[]) records.get(j))[3];//数组的第4个元素为列名
                        String fieldType = (String) ((Object[]) records.get(j))[7];//数组的第8个元素为列类型
                        fieldType = convert(fieldType);
                        result += "    public static " + fieldType + " " + StringKit.firstCharToLowerCase(fieldName) + ";\n";
                    }
                }
                result += "\n }";

                //写文件
                File f = new File(path, className + ".java");
                if (!f.exists()) {
                    f.createNewFile();
                }
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
                bw.write(result);
                bw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String convert(String fieldType) {
        if (fieldType.equalsIgnoreCase("varchar") || fieldType.equalsIgnoreCase("char")
                || fieldType.equalsIgnoreCase("blob") || fieldType.equalsIgnoreCase("text")) {
            return "String";
        } else if (fieldType.equalsIgnoreCase("int") || fieldType.equalsIgnoreCase("smallint")) {
            return "Integer";
        } else if (fieldType.equalsIgnoreCase("bit")) {
            return "Boolean";
        } else if (fieldType.equalsIgnoreCase("float") || fieldType.equalsIgnoreCase("double")) {
            return "Double";
        } else if (fieldType.equalsIgnoreCase("bigint")) {
            return "Long";
        } else if (fieldType.equalsIgnoreCase("datetime")) {
            return "java.sql.TimeStamp";
        } else {
            return "String";
        }
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        AutoCreateEntity.process("d:/", "piaohao.entity", true);
    }
}